"""
Django表单定义
"""

from django import forms
from django.core.exceptions import ValidationError
from .models import CloudAccount, Domain, DNSRecord, CloudProvider, RecordType


class CloudAccountForm(forms.ModelForm):
    """云账号表单"""
    
    secret_key = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入Secret Key'
        }),
        required=False,  # 编辑时可选
        help_text='留空则不修改现有密钥'
    )
    
    class Meta:
        model = CloudAccount
        fields = ['name', 'provider', 'access_key', 'secret_key', 'region', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入账号名称'
            }),
            'provider': forms.Select(attrs={
                'class': 'form-select'
            }),
            'access_key': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入Access Key'
            }),
            'region': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '地域（可选）'
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            })
        }
    
    def clean_name(self):
        name = self.cleaned_data.get('name')
        if len(name.strip()) < 2:
            raise ValidationError('账号名称至少需要2个字符')
        return name.strip()
    
    def clean_access_key(self):
        access_key = self.cleaned_data.get('access_key')
        if len(access_key.strip()) < 10:
            raise ValidationError('Access Key 格式不正确')
        return access_key.strip()


class DomainForm(forms.ModelForm):
    """域名表单"""
    
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        if self.user:
            self.fields['cloud_account'].queryset = CloudAccount.objects.filter(
                user=self.user,
                is_active=True
            )
    
    class Meta:
        model = Domain
        fields = ['name', 'cloud_account', 'zone_id', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入域名，如：example.com'
            }),
            'cloud_account': forms.Select(attrs={
                'class': 'form-select'
            }),
            'zone_id': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Zone ID（可选，某些云服务商需要）'
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            })
        }
    
    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name:
            raise ValidationError('域名不能为空')
        
        # 简单的域名格式验证
        import re
        pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$'
        if not re.match(pattern, name.strip()):
            raise ValidationError('请输入有效的域名格式')
        
        return name.strip().lower()


class DNSRecordForm(forms.ModelForm):
    """DNS记录表单"""
    
    class Meta:
        model = DNSRecord
        fields = ['name', 'record_type', 'value', 'ttl', 'priority', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '主机记录，如：www、@、*'
            }),
            'record_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'value': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '记录值'
            }),
            'ttl': forms.NumberInput(attrs={
                'class': 'form-control',
                'min': 60,
                'max': 86400
            }),
            'priority': forms.NumberInput(attrs={
                'class': 'form-control',
                'min': 0,
                'max': 100
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            })
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 为不同的记录类型设置不同的帮助文本
        self.fields['record_type'].help_text = '选择DNS记录类型'
        self.fields['priority'].help_text = '仅MX记录需要设置优先级'
        self.fields['ttl'].help_text = 'TTL值，范围：60-86400秒'
    
    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name:
            raise ValidationError('主机记录不能为空')
        
        # 基本的主机记录格式验证
        import re
        if name != '@' and name != '*':
            pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$'
            if not re.match(pattern, name):
                raise ValidationError('主机记录格式不正确')
        
        return name.strip()
    
    def clean_value(self):
        value = self.cleaned_data.get('value')
        record_type = self.cleaned_data.get('record_type')
        
        if not value:
            raise ValidationError('记录值不能为空')
        
        # 根据记录类型进行不同的验证
        if record_type == 'A':
            # IPv4地址验证
            import ipaddress
            try:
                ipaddress.IPv4Address(value.strip())
            except:
                raise ValidationError('请输入有效的IPv4地址')
        
        elif record_type == 'AAAA':
            # IPv6地址验证
            import ipaddress
            try:
                ipaddress.IPv6Address(value.strip())
            except:
                raise ValidationError('请输入有效的IPv6地址')
        
        elif record_type == 'CNAME':
            # CNAME记录验证
            if not value.strip().endswith('.'):
                value = value.strip() + '.'
        
        return value.strip()
    
    def clean(self):
        cleaned_data = super().clean()
        record_type = cleaned_data.get('record_type')
        priority = cleaned_data.get('priority')
        
        # MX记录必须设置优先级
        if record_type == 'MX' and (priority is None or priority < 0):
            raise ValidationError({'priority': 'MX记录必须设置优先级（大于等于0）'})
        
        return cleaned_data